package com.yc.testupload;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.servlet.ServletHolder;
import com.yc.testupload.controller.FileUploadServlet;
import com.yc.testupload.controller.DocumentsServlet;
import com.yc.testupload.controller.LoginServlet;
import com.yc.testupload.controller.RegisterServlet;
import com.yc.testupload.controller.CheckLoginStatusServlet;
import com.yc.testupload.controller.CheckDuplicateTitleServlet;
import com.yc.testupload.controller.DatabaseConfigServlet;
import com.yc.testupload.controller.CrawlerServlet;
import com.yc.testupload.controller.MaterialServlet;
import com.yc.testupload.controller.MaterialSaveServlet;
import com.yc.testupload.controller.MaterialInsertServlet;
import com.yc.testupload.controller.CategoryServlet;
import com.yc.testupload.controller.AccountsServlet;
import com.yc.testupload.controller.LogoutServlet;
import com.yc.testupload.controller.DocumentSaveServlet;
import com.yc.testupload.controller.FileProxyServlet;
import com.yc.testupload.controller.GetUserIdServlet;
import com.yc.testupload.controller.DatabaseTestServlet;
import com.yc.testupload.controller.WordForMaterialUploadServlet;
import com.yc.testupload.controller.EnvironmentConfigServlet;
import com.yc.testupload.controller.HelloServlet;
import com.yc.testupload.controller.TestServlet;
import com.yc.testupload.controller.MigrationServlet;
import com.yc.testupload.controller.WechatAccountServlet;
import java.io.File;
import java.net.URL;

public class FileUploadApplication {
    public static void main(String[] args) throws Exception {
        // 创建 Jetty 服务器，监听 8899 端口
        Server server = new Server(8899);

        // 使用 WebAppContext 以支持加载 webapp 目录下的静态资源
        WebAppContext context = new WebAppContext();

        // 设置上下文路径
        context.setContextPath("/");

        // 配置 webapp 目录路径
        // 处理在 JAR 包内和外部运行的不同情况

        // 首先尝试从类加载器中查找 webapp 资源（适用于JAR包内运行）
        URL webappResource = FileUploadApplication.class.getClassLoader().getResource("webapp/");
        if (webappResource != null) {
            // 从JAR包内加载webapp资源
            context.setResourceBase(webappResource.toExternalForm());
            context.setWar(webappResource.toExternalForm());
        } else {
            // 在开发环境或JAR包外运行时，尝试多种可能的路径
            String[] possiblePaths = {
                    "src/main/webapp/", // 开发环境下的标准路径
                    System.getProperty("user.dir") + File.separator + "webapp", // 当前工作目录下的webapp
                    System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator
                            + "webapp" // 当前工作目录下的完整源码路径
            };

            boolean found = false;
            for (String path : possiblePaths) {
                File webappDir = new File(path);
                if (webappDir.exists() && webappDir.isDirectory()) {
                    context.setResourceBase(path);
                    context.setWar(path);
                    found = true;
                    break;
                }
            }

            // 如果都找不到，输出警告但继续启动
            if (!found) {
                System.err.println("警告: 未找到webapp目录资源。请确保webapp目录正确打包或位于可访问路径。");
                // 设置默认路径，至少让服务器能启动
                context.setResourceBase(System.getProperty("user.dir"));
                context.setWar(System.getProperty("user.dir"));
            }
        }

        System.out.println("使用的资源基础路径: " + context.getResourceBase());

        // 设置类加载器，确保能加载到 webapp 中的资源
        context.setClassLoader(Thread.currentThread().getContextClassLoader());

        // 配置默认欢迎页
        context.setWelcomeFiles(new String[] { "index.html" });

        // 显式注册 Servlet
        ServletHolder fileUploadServletHolder = new ServletHolder("fileUploadServlet", FileUploadServlet.class);
        // 显式配置 MultipartConfig，确保文件上传功能正常工作
        fileUploadServletHolder.getRegistration().setMultipartConfig(
                new jakarta.servlet.MultipartConfigElement(
                        null, // 临时文件目录（使用默认）
                        50 * 1024 * 1024, // 最大文件大小 50MB
                        55 * 1024 * 1024, // 最大请求大小 55MB
                        1024 * 1024 // 文件大小阈值 1MB
                ));
        context.addServlet(fileUploadServletHolder, "/upload");

        // 显式注册 DocumentsServlet，确保/api/documents/*路径可访问
        ServletHolder documentsServletHolder = new ServletHolder("documentsServlet", DocumentsServlet.class);
        context.addServlet(documentsServletHolder, "/api/documents/*");

        // 显式注册 LoginServlet，确保/login路径可访问
        ServletHolder loginServletHolder = new ServletHolder("loginServlet", LoginServlet.class);
        context.addServlet(loginServletHolder, "/login");

        // 显式注册 RegisterServlet，确保/register路径可访问
        ServletHolder registerServletHolder = new ServletHolder("registerServlet", RegisterServlet.class);
        context.addServlet(registerServletHolder, "/register");

        // 显式注册 CheckLoginStatusServlet，确保/check-login路径可访问
        ServletHolder checkLoginStatusServletHolder = new ServletHolder("checkLoginStatusServlet",
                CheckLoginStatusServlet.class);
        context.addServlet(checkLoginStatusServletHolder, "/check-login");

        // 显式注册 LogoutServlet，确保/logout路径可访问
        ServletHolder logoutServletHolder = new ServletHolder("logoutServlet", LogoutServlet.class);
        context.addServlet(logoutServletHolder, "/logout");

        // 显式注册 CheckDuplicateTitleServlet，确保/check-duplicate路径可访问
        ServletHolder checkDuplicateTitleServletHolder = new ServletHolder("checkDuplicateTitleServlet",
                CheckDuplicateTitleServlet.class);
        context.addServlet(checkDuplicateTitleServletHolder, "/check-duplicate");

        // 显式注册 DatabaseConfigServlet，确保/DatabaseConfigServlet路径可访问
        ServletHolder databaseConfigServletHolder = new ServletHolder("databaseConfigServlet",
                DatabaseConfigServlet.class);
        context.addServlet(databaseConfigServletHolder, "/DatabaseConfigServlet");

        // 显式注册 CrawlerServlet，确保/api/crawl路径可访问
        ServletHolder crawlerServletHolder = new ServletHolder("crawlerServlet", CrawlerServlet.class);
        context.addServlet(crawlerServletHolder, "/api/crawl");

        // 显式注册 MaterialServlet，确保/api/materials路径可访问
        ServletHolder materialServletHolder = new ServletHolder("materialServlet", MaterialServlet.class);
        context.addServlet(materialServletHolder, "/api/materials");

        // 显式注册 MaterialSaveServlet，确保/api/saveToMaterial路径可访问
        ServletHolder materialSaveServletHolder = new ServletHolder("materialSaveServlet", MaterialSaveServlet.class);
        context.addServlet(materialSaveServletHolder, "/api/saveToMaterial");

        // 显式注册 MaterialInsertServlet，确保/api/insert-materials路径可访问
        ServletHolder materialInsertServletHolder = new ServletHolder("materialInsertServlet",
                MaterialInsertServlet.class);
        context.addServlet(materialInsertServletHolder, "/api/insert-materials");

        // 显式注册 EnvironmentConfigServlet，确保/api/environment-config路径可访问
        ServletHolder environmentConfigServletHolder = new ServletHolder("environmentConfigServlet",
                com.yc.testupload.controller.EnvironmentConfigServlet.class);
        context.addServlet(environmentConfigServletHolder, "/api/environment-config");

        // 显式注册 CategoryServlet，确保/api/categories路径可访问
        ServletHolder categoryServletHolder = new ServletHolder("categoryServlet", CategoryServlet.class);
        context.addServlet(categoryServletHolder, "/api/categories");
        
        // 显式注册 AccountsServlet，确保/api/accounts路径可访问
        ServletHolder accountsServletHolder = new ServletHolder("accountsServlet", AccountsServlet.class);
        context.addServlet(accountsServletHolder, "/api/accounts");

        // 显式注册 DocumentSaveServlet，确保/api/save-document路径可访问
        ServletHolder documentSaveServletHolder = new ServletHolder("documentSaveServlet", DocumentSaveServlet.class);
        context.addServlet(documentSaveServletHolder, "/api/save-document");
        
        // 显式注册 PublishServlet，确保/api/publish路径可访问
        ServletHolder publishServletHolder = new ServletHolder("publishServlet", com.yc.testupload.controller.PublishServlet.class);
        context.addServlet(publishServletHolder, "/api/publish");

        // 显式注册 FileProxyServlet
        ServletHolder fileProxyServletHolder = new ServletHolder("fileProxyServlet", FileProxyServlet.class);
        context.addServlet(fileProxyServletHolder, "/proxy/*");

        // 显式注册 GetUserIdServlet
        ServletHolder getUserIdServletHolder = new ServletHolder("getUserIdServlet", GetUserIdServlet.class);
        context.addServlet(getUserIdServletHolder, "/get-user-id");

        // 显式注册 DatabaseTestServlet
        ServletHolder databaseTestServletHolder = new ServletHolder("databaseTestServlet", DatabaseTestServlet.class);
        context.addServlet(databaseTestServletHolder, "/database-test");

        // 显式注册 HelloServlet
        ServletHolder helloServletHolder = new ServletHolder("helloServlet", HelloServlet.class);
        context.addServlet(helloServletHolder, "/hello");

        // 显式注册 TestServlet
        ServletHolder testServletHolder = new ServletHolder("testServlet", TestServlet.class);
        context.addServlet(testServletHolder, "/test");

        // 显式注册 MigrationServlet
        ServletHolder migrationServletHolder = new ServletHolder("migrationServlet", MigrationServlet.class);
        context.addServlet(migrationServletHolder, "/migrate");

        // 显式注册 WechatAccountServlet
        ServletHolder wechatAccountServletHolder = new ServletHolder("wechatAccountServlet", WechatAccountServlet.class);
        context.addServlet(wechatAccountServletHolder, "/api/wechat-account");

        // 将上下文处理器添加到服务器
        server.setHandler(context);

        // 启动服务器
        System.out.println("启动 Jetty 服务器，监听端口: 8899");
        server.start();
        System.out.println("可以通过 http://localhost:8899/index.html 访问页面");
        // 等待服务器停止
        server.join();
    }
}